using Avalonia.BiliBili.Units;
using Avalonia.BiliBili.Views.ChildViews.Search;
using Avalonia.Extensions.Controls;
using Avalonia.Extensions.Event;
using Bilibili.Common;
using Bilibili.Model.Common;
using Bilibili.Model.Search;
using DynamicData;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace Avalonia.BiliBili.Views.ChildViews
{
    public partial class SearchArticle : ChildView
    {
        private int PageNum { get; set; } = 1;
        private ObservableCollection<SearchArticleItem> Items { get; }
        public SearchArticle()
        {
            InitializeComponent();
            Items = [];
        }
        public override void Callback(object data)
        {
            RunOnUiThread(async () =>
            {
                if (data is InvokeData<string> info)
                {
                    if (info.Clear)
                        Items.Clear();
                    string order = "totalrank", region = "0";
                    var result = await Base.Client.GetArticles(info.Data, order, region, PageNum);
                    if (result.IsSuccess())
                    {
                        var model = result.Data["result"].ToObject<List<SearchArticleItem>>();
                        Items.AddRange(model);
                    }
                    else
                        PopupToast.Show(result?.Message);
                }
            });
        }
        public override void AfterInitializeComponent()
        {
            articleList.ItemsSource = Items;
            articleList.ItemClick += ArticleList_ItemClick;
        }
        private void ArticleList_ItemClick(object? sender, ViewRoutedEventArgs e)
        {
            try
            {
                if (e.IsLeftClick && e.ClickItem is ListViewItem item && item.Content is SearchArticleItem articleItem)
                    Navigater.OpenWebView($"https://www.bilibili.com/read/app/{articleItem.id}", true);
            }
            catch { }
        }
    }
}